import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
// 通过 cookie 的方式保存已登录状态
const String uri = 'https://geekailab.com/io/flutter-trip/Flutter2JSByUrl.html?name=geekailabcc';
class FlutterH5AuthCookie extends StatefulWidget {
  const FlutterH5AuthCookie({super.key});

  @override
  State<FlutterH5AuthCookie> createState() => _FlutterH5AuthCookieState();
}

class _FlutterH5AuthCookieState extends State<FlutterH5AuthCookie> {
  WebViewCookieManager cookieManager = WebViewCookieManager();
  late WebViewController controller;

  get _loadBtn => FilledButton(onPressed: (){
    controller.loadRequest(Uri.parse(uri));
  }, child: const Text('加载H5页面'));

  get _setCookie => FilledButton(onPressed: (){
    _onSetCookie(context);
  }, child: const Text('加载cookie', style: TextStyle(color: Colors.white),));

  get _clearCookie => FilledButton(onPressed: (){
    _onClearCookie(context);
  }, child: const Text('清除cookie', style: TextStyle(color:Colors.white),));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('cookie保存登录状态'),
        actions: [_loadBtn,_setCookie,_clearCookie],
      ),
      body: WebViewWidget(controller: controller),
    );
  }
  @override
  void initState() {
    super.initState();
    controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted);
  }

  // 保存cookie
  void _onSetCookie(BuildContext context) async {
    // 设置登录状态 token
    await cookieManager.setCookie(WebViewCookie(
      name: 'token',// cookie 名称
      value: 'my custom cookie',// cookie 值
      domain: 'geekailab.com',// cookie作用的域名
      path: '/',// 域名下的路径，可以缺省，弱设置一个具体的 path 则只有这个 path 下的网址才可以获取到保存的 cookie
    ));

    // 设置用户工号
    await cookieManager.setCookie(WebViewCookie(
      name: 'uid',// cookie 名称
      value: '1001',// cookie 值
      domain: 'geekailab.com',// cookie作用的域名
      path: '/',// 域名下的路径，可以缺省，弱设置一个具体的 path 则只有这个 path 下的网址才可以获取到保存的 cookie
    ));

    // flutter 中获取 cookie
    final Object cookies = await controller.runJavaScriptReturningResult('document.cookie');
    print('flutter获取到的cookie:$cookies');
  }

  // 清除cookie
  void _onClearCookie(BuildContext context) async {
    await cookieManager.clearCookies();
    print('已清除cookie');
  }
}
